package com.thinkgem.jeesite.common.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class WxPayCommonUtil {
	//浩博数码公众号
	/*public static String APPID_P = "wx22f4c2075410b077";
	public static String APPSecret_P = "11635d4cb2f85b9983f83e99a688e301";
	public static String API_KEY_P = "000000fc008000e40087b8c7d8b9aaaa";
	public static String MCH_ID_P = "1449896402";*/
	
	//少先队网商户平台 公众号
	public static String APPID = "wx94a20ddeff0bbd9b"; // 微信公众平台  开发-基本配置
	public static String APPSecret = "bc8511e47dc4e297dd8772a7bd7177c4"; // 微信公众平台  开发-基本配置
	public static String API_KEY = "c48601be90714045a13147331c5512ad"; // 微信商户平台  账户中心-账户设置-API安全-API秘钥-设置API密钥
	public static String MCH_ID = "1490368442"; // 微信商户平台  账户中心-账户设置-商户信息-基本账户信息

	// ����ַ�������
	public static String getRandomString(int length) { // length��ʾ�����ַ����ĳ���
		String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	// ����xml��װ
	public static String getRequestXml(SortedMap<String, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String key = (String) entry.getKey();
			String value = (String) entry.getValue();
			if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key) || "sign".equalsIgnoreCase(key)) {
				sb.append("<" + key + ">" + "<![CDATA[" + value + "]]></" + key + ">");
			} else {
				sb.append("<" + key + ">" + value + "</" + key + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}

	// ����ǩ��
	public static String createSign(String characterEncoding, SortedMap<String, Object> parameters,String proxyName) {
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		/*if("浩博数码".equals(proxyName)){
			sb.append("key=" + API_KEY_P);
		}else{*/
			sb.append("key=" + API_KEY);
		// }
		
		String sign = MD5.md5(sb.toString()).toUpperCase();
		return sign;
	}

	// ���󷽷�
	public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		try {

			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// ��������ʽ��GET/POST��
			conn.setRequestMethod(requestMethod);
			conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
			// ��outputStr��Ϊnullʱ�������д����
			if (null != outputStr) {
				OutputStream outputStream = conn.getOutputStream();
				// ע������ʽ
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// ����������ȡ��������
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			// �ͷ���Դ
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			return buffer.toString();
		} catch (ConnectException ce) {
			System.out.println("���ӳ�ʱ��{}" + ce);
		} catch (Exception e) {
			System.out.println("https�����쳣��{}" + e);
		}
		return null;
	}

	/*
	 * //�˿�����󷽷� public static String httpsRequest2(String requestUrl, String
	 * requestMethod, String outputStr) throws Exception { KeyStore keyStore =
	 * KeyStore.getInstance("PKCS12"); StringBuilder res = new
	 * StringBuilder(""); FileInputStream instream = new FileInputStream(new
	 * File("/home/apiclient_cert.p12")); try { keyStore.load(instream,
	 * "".toCharArray()); } finally { instream.close(); }
	 * 
	 * // Trust own CA and all self-signed certs SSLContext sslcontext =
	 * SSLContexts.custom() .loadKeyMaterial(keyStore,
	 * "1313329201".toCharArray()) .build(); // Allow TLSv1 protocol only
	 * SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
	 * sslcontext, new String[] { "TLSv1" }, null,
	 * SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
	 * CloseableHttpClient httpclient = HttpClients.custom()
	 * .setSSLSocketFactory(sslsf) .build(); try {
	 * 
	 * HttpPost httpost = new
	 * HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
	 * httpost.addHeader("Connection", "keep-alive");
	 * httpost.addHeader("Accept", ""); httpost.addHeader("Content-Type",
	 * "application/x-www-form-urlencoded; charset=UTF-8");
	 * httpost.addHeader("Host", "api.mch.weixin.qq.com");
	 * httpost.addHeader("X-Requested-With", "XMLHttpRequest");
	 * httpost.addHeader("Cache-Control", "max-age=0");
	 * httpost.addHeader("User-Agent",
	 * "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) "); StringEntity
	 * entity2 = new StringEntity(outputStr ,Consts.UTF_8);
	 * httpost.setEntity(entity2); System.out.println("executing request" +
	 * httpost.getRequestLine());
	 * 
	 * CloseableHttpResponse response = httpclient.execute(httpost);
	 * 
	 * try { HttpEntity entity = response.getEntity();
	 * 
	 * System.out.println("----------------------------------------");
	 * System.out.println(response.getStatusLine()); if (entity != null) {
	 * System.out.println("Response content length: " +
	 * entity.getContentLength()); BufferedReader bufferedReader = new
	 * BufferedReader(new InputStreamReader(entity.getContent())); String
	 * text;res.append(text); while ((text = bufferedReader.readLine()) != null)
	 * { res.append(text); System.out.println(text); }
	 * 
	 * } EntityUtils.consume(entity); } finally { response.close(); } } finally
	 * { httpclient.close(); } return res.toString();
	 * 
	 * }
	 */
	// xml����
	public static Map doXMLParse(String strxml) throws JDOMException, IOException {
		strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

		if (null == strxml || "".equals(strxml)) {
			return null;
		}

		Map m = new HashMap();

		InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}

			m.put(k, v);
		}

		// �ر���
		in.close();

		return m;
	}

	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}
	
	
	
}
